/**
 * 处理设备数据实时websocket，用于设备查看时实时反馈
 * 
 * 
 */
 import { formatDate } from '@/utils/util'
import md5 from 'js-md5'

 export const WebSocketDeviceListMixins = {
    data(){
      return {
        disableMixinCreated:false,
        lockReconnect: false,
        dataJson: {},
      }
    },
    created() {
        if(!this.disableMixinCreated){
          console.log(' -- device mixin created -- ')
        }
    },
    computed: {
      
    },
    methods:{
      initWebSocket: function (uuid) {
        // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
        // var userId = store.getters.userInfo.id;
        //let md555 = md5(uuid);
        var url = window._CONFIG['WS_URL']+"/deviceListWebsocket/"+uuid+"/";
        console.log("svalue",url)
        this.websock = new WebSocket(url);
        this.websock.onopen = this.websocketOnopen;
        this.websock.onerror = this.websocketOnerror;
        this.websock.onmessage = this.websocketOnmessage;
        this.websock.onclose = this.websocketOnclose;
      },
      websocketOnopen: function () {
        console.log("设备WebSocket连接成功");
      },
      websocketOnerror: function (e) {
        console.log("设备WebSocket连接发生错误");
        this.reconnect();
      },
      closeWS: function (){
        this.websock.close();
      },
      websocketOnmessage: function (e) {
        var data = eval("(" + e.data + ")"); //解析对象
        if (data.shadow != null) {
          this.json = data.shadow;
          this.record = data;
        }
        else{
          this.json = data;
        }
        if(data.cmd){
          if(data.cmd == 'ACK'){
            if(data.cmdStr == ""){
              this.$message.info("指令成功下发")              
            }else{
              _that.$message.info("指令下发失败")
            }
          }
          this.resolveData(data);
        }
      },
      resolveData:function(dData){
        console.log("这个方法需要被继承");
      },
      websocketOnclose: function (e) {
        console.log("connection closed (" + e + ")");
        if(e){
          console.log("connection closed (" + e.code + ")");
        }
        this.reconnect();
      },
      websocketSend(text) { // 数据发送
        try {
          this.websock.send(text);
        } catch (err) {
          console.log("send failed (" + err.code + ")");
        }
      },
      reconnect() {
        var that = this;
        if(that.lockReconnect) return;
        that.lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(function () {
          console.info("尝试重连...");
          that.initWebSocket();
          that.lockReconnect = false;
        }, 5000);
      },
    }
}